package com.ma.chapter4.t4;

import lombok.extern.slf4j.Slf4j;

import static com.ma.util.Sleeper.sleep;

/**
 * @ClassName TestRoom
 * @Author: mayongqiang
 * @DATE 2022/3/8 20:13
 * @Description:
 */
@Slf4j(topic = "m.test")
public class TestRoom {
    static final Object room = new Object();
    static boolean hasCigarette = false;
    static boolean hasTakeout = false;

    public static void main(String[] args) {
        new Thread(() -> {
            synchronized (room) {
                log.debug("有烟没？[{}]", hasCigarette);
                //用while 解决虚假唤醒问题
                while (!hasCigarette) {
                    log.debug("没烟，先歇会");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("有烟没？[{}]", hasCigarette);
                if (hasCigarette) {
                    log.debug("可以开始干活了");
                } else {
                    log.debug("没干活...");
                }

            }
        }, "小南").start();
        new Thread(() -> {
            synchronized (room) {
                Thread thread = Thread.currentThread();
                log.debug("外卖到没？[{}]", hasTakeout);
                if (!hasTakeout) {
                    log.debug("没到，先歇会");
                    try {
                        room.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                log.debug("外卖到没？[{}]", hasTakeout);
                if (hasTakeout) {
                    log.debug("可以开始干活了");
                } else {
                    log.debug("没干活...");
                }

            }
        }, "小女").start();


        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                synchronized (room) {
                    log.debug("可以开始干活了");
                }
            }, "其他人").start();
        }

        sleep(1);

        new Thread(() -> {
            synchronized (room) {
                hasTakeout = true;
                log.debug("外卖到了");
                try {
                    room.notifyAll();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, "送外卖的").start();


    }


}
